﻿@page "/logs/{ServiceName}"
@inject Application application
@implements IDisposable

<h3>Logs for @ServiceName</h3>

@if (ApplicationLogs == null)
{
    <span>Unknown service @ServiceName</span>
}
else
{
    <div style="padding:10px">
        <button type="button" class="btn btn-primary" @onclick=ClearLogs>Clear Log</button>
    </div>
    <div style="overflow-y: scroll;position: absolute;height: 84%; width:75%; color:white;background-color:black;padding:10px">
        @foreach (var log in ApplicationLogs)
        {
            <div style="width:100%">@log.Text</div>
        }
    </div>
}

@code {
    [Parameter]
    public string ServiceName { get; set; } = default!;

    public List<(string Text, int Id)>? ApplicationLogs { get; set; } 

    private IDisposable? _subscription;

    protected override void OnInitialized()
    {
        // TODO: handle this returning false
        if (application.Services.TryGetValue(ServiceName, out var service))
        {
            ApplicationLogs = service.CachedLogs.Select((item, index) => (item, index)).ToList();
            var count = ApplicationLogs.Count;

            _subscription = service.Logs.Subscribe(log =>
            {
                count++;
                InvokeAsync(() =>
                {
                    ApplicationLogs.Add((log, count));
                    StateHasChanged();
                });
            });
        }

        base.OnInitialized();
    }

    private void ClearLogs()
    {
        ApplicationLogs?.Clear();
    }

    void IDisposable.Dispose()
    {
        _subscription?.Dispose();
    }
}
